package com.sea.product.controller;


import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.product.entity.Category;
import com.sea.product.entity.Product;
import com.sea.product.service.CategoryService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/product/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        return "/sea/product/category/main";
    }

    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        Category category = categoryService.findById(id);
        model.addAttribute("category",category);
        return "/sea/product/category/edit";
    }

    @RequestMapping("/editBigPage")
    public String editBigPage(Model model,@RequestParam("id")Integer id) {
        Category category = categoryService.findById(id);
        model.addAttribute("category",category);
        return "/sea/product/category/editBig";
    }
    @RequestMapping("/editMidPage")
    public String editMidPage(Model model,@RequestParam("id")Integer id) {
        Category category = categoryService.findById(id);
        model.addAttribute("category",category);
        return "/sea/product/category/editMid";
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findCategory")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start
                                     ) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Category> list = categoryService.findCategory();
        PageInfo<Category> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByParentId")
    public List<Category> findByParentId(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Integer id) {
        return categoryService.findByParentId(id);
    }

    /**
     * 保存
     * @param category
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Category category) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != category && categoryService.save(category) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前品类不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 保存
     * @param category
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(Category category) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != category && categoryService.usave(category) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前品类不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response) {
        List<Product> list = categoryService.export();
        String[] title = {"大类","中类","小类"};
        String fileName = "品类信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "品类信息";
        String[][] content = new String[list.size()][3];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Product obj = list.get(i);
            content[i][0] = obj.getProductBigClassName();
            content[i][1] = obj.getProductMidClassName();
            content[i][2] = obj.getProductClassName();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
